import React, { useEffect, useState, useCallback } from 'react';
import { Select, notification } from 'antd';
import { fetchApi } from '../../general/api';

interface HostOption {
    value: number;
    label: string;
}

interface SelectProjectProps {
    projectId: string | undefined;
    selectedCity: number | undefined; // 选中
    onCityChange: (value: number, label: string) => void; // 处理选择的回调
    style?: React.CSSProperties;
    placeholderLabel?: string; // 新增：用于动态设置 '无' 的 label
}

const SelectHost: React.FC<SelectProjectProps> = ({
    selectedCity,
    onCityChange,
    style,
    projectId,
    placeholderLabel = '无', // 默认值为 '无'
}) => {
    const [HostOptions, setHostOptions] = useState<HostOption[]>([]);

    // 使用 useCallback 缓存 fetchHostOptions
    const fetchHostOptions = useCallback(async () => {
        if (!projectId) {
            setHostOptions([]); // 如果没有项目ID，清空选项
            return;
        }

        try {
            const response = await fetchApi(`/easymonitor/api/host?project_id=${projectId}`); // 修改请求使用 projectId
            const hosts = response.map((host: any) => ({
                value: host.host_id, // 确保有唯一 key
                label: host.host_name,
            }));
            setHostOptions(hosts); // 更新数据源
            notification.success({
                message: '请求成功',
                description: '主机数据查询成功。',
                duration: 2, // 2秒后自动关闭
            });
        } catch (error) {
            notification.error({
                message: '请求失败',
                description: '主机数据查询失败:' + error,
                duration: 2,
            });
        }
    }, [projectId]); // 将 projectId 作为依赖项

    useEffect(() => {
        fetchHostOptions(); // 组件挂载或 projectId 变化时请求数据
    }, [fetchHostOptions]); // 将 fetchHostOptions 添加到依赖数组

    // 处理选择变化
    const handleChange = (value: number) => {
        const selectedOption = HostOptions.find((option) => option.value === value);
        const label = selectedOption ? selectedOption.label : '';
        onCityChange(value, label); // 将 value 和 label 一起返回父组件
    };

    return (
        <Select
            style={style}
            showSearch
            value={selectedCity || undefined} // 确保 selectedCity 变化时更新 UI
            onChange={handleChange}
            options={[{ value: '', label: placeholderLabel }, ...HostOptions]} // 使用动态的 placeholderLabel
        />
    );
};

export default SelectHost;